import os
import Image

import mimetypes

from damn.util import GetScriptPath, RunBlenderURI, ParseOptionsMap, AssetPathAbsolute, BlenderDependency

from damn.transcoder import TranscoderFailedException, BaseTranscoder


BlenderDependency()

class BlenderImageTranscoder(BaseTranscoder):
  transcoder = True
  convert_map = {"application/x-blender.image" : ["image/jpeg", "image/png"]}
  _options = [('sizex', int, None), ('sizey', int, None),]
  options_map = {"application/x-blender.image" : _options,}

  def transcode(self, anAssetReference, dstFormat, **kwargs):
    filePath = super(BlenderImageTranscoder, self).transcode(anAssetReference, dstFormat, kwargs)
    
    environ = {}
    environ["BlenderImageTranscoder-image"] = anAssetReference.subName
    environ["BlenderImageTranscoder-path"] = filePath
    
    stdoutdata, stderrdata, returncode = RunBlenderURI(anAssetReference.file.fileName, GetScriptPath(__file__), None, environ)
    
    if returncode != 0: raise TranscoderFailedException('BlenderImageTranscoder failed! returncode %s.'%(returncode))
    
    if kwargs['sizex'] or kwargs['sizey']:
      try:  
        im = Image.open(filePath)
      except IOError:
        print "cannot open", filePath
        return False
      
      size, differ = self.normalize_size(kwargs, im)      
        
      if differ:  
        im.thumbnail((size[0], size[1]))
        im.save(filePath)
    
    return filePath    
